const app = getApp();

Page({
    data: {
        isLoggedIn: false,  // 登录状态
        currentFilter: 'all',
        filterNames: {
            all: '全部',
            unread: '未读',
            system: '系统'
        },
        orderStats: {
            newOrders: 0,        // 新订单数量
            pendingOrders: 0,    // 待处理订单数量
            monthlyIncome: 0     // 当月进账
        },
        messages: [
            {
                id: 1,
                type: 'new_order',
                typeName: '新订单',
                title: '新订单通知',
                content: '您有一单新的外卖订单，订单号：LX202506190001，配送费：¥8.5',
                time: '刚刚',
                isRead: false,
                actions: [
                    {type: 'accept', text: '立即接单'}
                ]
            },
            {
                id: 2,
                type: 'delivery',
                typeName: '配送中',
                title: '配送提醒',
                content: '订单LX202506190001，客户催促加快配送，预计还需15分钟送达。',
                time: '5分钟前',
                isRead: false,
                actions: [
                    {type: 'contact', text: '联系客户'}
                ]
            },
            {
                id: 3,
                type: 'pickup',
                typeName: '待取货',
                title: '取餐通知',
                content: '订单LX202506190002，商家已准备好，请尽快到店取餐。',
                time: '10分钟前',
                isRead: false
            },
            {
                id: 4,
                type: 'new_order',
                typeName: '新订单',
                title: '平台维护通知',
                content: '平台将于本周日凌晨2:00-6:00进行系统维护，期间暂停接单服务。',
                time: '1小时前',
                isRead: true
            },
            {
                id: 5,
                type: 'new_order',
                typeName: '新订单',
                title: '高价值订单',
                content: '您有一单高价值订单，订单号：LX202506190003，配送费：¥15.0',
                time: '2小时前',
                isRead: true
            },
            {
                id: 6,
                type: 'new_order',
                typeName: '新订单',
                title: '评分提醒',
                content: '您的服务评分为4.9分，继续保持优质服务，获得更多奖励！',
                time: '今天 14:30',
                isRead: true
            }
        ],
        filteredMessages: [],
        unreadCount: 0,
        todayCount: 0,
        refreshTimer: null, // 定时器
        customerServiceUnreadCount: 0 // 客服未读消息数量
    },

    onLoad() {
        this.checkLoginStatus();
        if (this.data.isLoggedIn) {
            this.fetchOrderMessages();
            this.fetchOrderStats();
            this.fetchCustomerServiceUnreadCount(); // 获取客服未读消息
            this.startAutoRefresh(); // 启动自动刷新
        }
    },

    onShow() {
        this.checkLoginStatus();
        if (this.data.isLoggedIn) {
            this.fetchOrderMessages();
            this.fetchOrderStats();
            this.fetchCustomerServiceUnreadCount(); // 获取客服未读消息
            this.startAutoRefresh(); // 启动自动刷新
        }
    },

    onHide() {
        this.stopAutoRefresh(); // 停止自动刷新
    },

    onUnload() {
        this.stopAutoRefresh(); // 停止自动刷新
    },

    // 启动自动刷新
    startAutoRefresh() {
        // 先清除之前的定时器
        this.stopAutoRefresh();const timer = setInterval(() => {
            if (this.data.isLoggedIn) {this.fetchOrderMessages();
                this.fetchOrderStats();
                this.fetchMonthlyIncome(); // 同时刷新当月收入
                this.fetchCustomerServiceUnreadCount(); // 刷新客服未读消息
            }
        }, 30000); // 30秒刷新一次

        this.setData({
            refreshTimer: timer
        });
    },

    // 停止自动刷新
    stopAutoRefresh() {
        if (this.data.refreshTimer) {clearInterval(this.data.refreshTimer);
            this.setData({
                refreshTimer: null
            });
        }
    },

    // 检查登录状态
    checkLoginStatus() {
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        const isLoggedIn = !!(token && riderId);
        this.setData({isLoggedIn});

        if (!isLoggedIn) {
            // 未登录时清空消息数据
            this.setData({
                filteredMessages: [],
                unreadCount: 0,
                todayCount: 0,
                orderStats: {
                    newOrders: 0,
                    pendingOrders: 0,
                    monthlyIncome: 0
                }
            });
        }
    },

    // 跳转到登录页面
    goToLogin() {
        wx.navigateTo({
            url: '/pages/logs/logs'
        });
    },

    // 跳转到客服页面
    goToCustomerService() {
        wx.navigateTo({
            url: '/pages/customer-service/index'
        });
    },

    // 获取订单消息
    fetchOrderMessages() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        if (!token || !riderId) {
            return;
        }let allMessages = [];

        // 获取新订单消息
        wx.request({
            url: `${ip}/api/orders/listNoOrdersReceived`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {if (res.data.code === 200) {
                    const allOrders = res.data.data || [];const newOrders = allOrders.filter(item =>
                        item.orderStatusName === '待接单' || item.orderStatus === 1
                    );
                    // 生成新订单消息
                    newOrders.forEach(order => {
                        const amount = order.paidAmount || order.actualAmount || order.totalAmount || order.amount || 0;

                        allMessages.push({
                            id: `new_${order.orderId || order.id}`,
                            type: 'new_order',
                            typeName: '新订单',
                            title: '新订单通知',
                            content: `您有一单新的外卖订单，订单号：${order.orderSn || order.orderNumber || order.orderId || order.id}，实付金额：¥${amount}`,
                            time: this.formatTime(order.createTime),
                            isRead: false,
                            icon: '🆕',
                            actions: [{
                                text: '立即接单',
                                type: 'primary',
                                action: 'acceptOrder',
                                orderId: order.orderId || order.id
                            }]
                        });
                    });
                }
                this.fetchPickupMessages(allMessages);
            },
            fail: (err) => {this.fetchPickupMessages(allMessages);
            }
        });
    },

    // 获取取货消息
    fetchPickupMessages(allMessages) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 获取已接单待取货的订单
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=2`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const pickupOrders = res.data.data || [];

                    // 生成取货消息
                    pickupOrders.forEach(order => {
                        allMessages.push({
                            id: `pickup_${order.orderId || order.id}`,
                            type: 'pickup',
                            typeName: '待取货',
                            title: '取餐通知',
                            content: `订单${order.orderSn || order.orderNumber || order.orderId}，商家已准备好，请前往取餐。`,
                            time: this.formatTime(order.updateTime),
                            isRead: false,
                            icon: '🏪',
                            actions: [{
                                text: '商家提醒',
                                type: 'secondary',
                                action: 'contactMerchant',
                                orderId: order.orderId || order.id
                            }]
                        });
                    });
                }
                this.fetchDeliveryMessages(allMessages);
            },
            fail: (err) => {this.fetchDeliveryMessages(allMessages);
            }
        });
    },

    // 获取配送中消息
    fetchDeliveryMessages(allMessages) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 获取配送中的订单
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=3`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const deliveryOrders = res.data.data || [];

                    // 生成配送中消息
                    deliveryOrders.forEach(order => {
                        allMessages.push({
                            id: `delivery_${order.orderId || order.id}`,
                            type: 'delivery',
                            typeName: '配送中',
                            title: '配送提醒',
                            content: `订单${order.orderSn || order.orderNumber || order.orderId}，客户催促加快配送，预计还需15分钟送达。`,
                            time: this.formatTime(order.updateTime),
                            isRead: false,
                            icon: '🔔',
                            actions: [{
                                text: '联系客户',
                                type: 'secondary',
                                action: 'contactCustomer',
                                orderId: order.orderId || order.id
                            }]
                        });
                    });
                }
                this.fetchDeliveryReadyMessages(allMessages);
            },
            fail: (err) => {this.fetchDeliveryReadyMessages(allMessages);
            }
        });
    },

    // 获取待收货消息
    fetchDeliveryReadyMessages(allMessages) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 获取待收货的订单 (orderStatus=4)
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=4`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const deliveryReadyOrders = res.data.data || [];

                    // 生成待收货消息
                    deliveryReadyOrders.forEach(order => {
                        allMessages.push({
                            id: `delivery_ready_${order.orderId || order.id}`,
                            type: 'delivery_ready',
                            typeName: '待收货',
                            title: '送达提醒',
                            content: `订单${order.orderSn || order.orderNumber || order.orderId}已送达目的地，请确认客户收货。`,
                            time: this.formatTime(order.updateTime),
                            isRead: false,
                            icon: '📦',
                            actions: [{
                                text: '确认送达',
                                type: 'primary',
                                action: 'confirmDelivery',
                                orderId: order.orderId || order.id
                            }]
                        });
                    });
                }
                this.fetchCompletedMessages(allMessages);
            },
            fail: (err) => {this.fetchCompletedMessages(allMessages);
            }
        });
    },

    // 获取已完成订单消息
    fetchCompletedMessages(allMessages) {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        // 不显示已完成的订单，直接更新消息数据
        this.updateMessages(allMessages);
    },

    // 更新消息数据
    updateMessages(allMessages) {

        // 检查是否有客服未读消息，如果有则添加到消息列表
        if (this.data.customerServiceUnreadCount > 0) {
            const customerServiceMessage = {
                id: 'customer_service',
                type: 'customer_service',
                typeName: '客服消息',
                title: '客服消息',
                content: `您有${this.data.customerServiceUnreadCount}条未读的客服消息，请及时查看回复。`,
                time: '刚刚',
                isRead: false,
                icon: '💬',
                priority: 1,
                actions: [{
                    text: '查看消息',
                    type: 'primary',
                    action: 'viewCustomerService'
                }]
            };

            // 检查是否已存在客服消息，避免重复添加
            const existingIndex = allMessages.findIndex(msg => msg.id === 'customer_service');
            if (existingIndex >= 0) {
                // 更新现有的客服消息
                allMessages[existingIndex] = customerServiceMessage;
            } else {
                // 添加新的客服消息到顶部
                allMessages.unshift(customerServiceMessage);
            }} else {
            // 移除客服消息（如果存在）
            allMessages = allMessages.filter(msg => msg.id !== 'customer_service');}

        // 按时间排序，最新的在前（客服消息优先级最高）
        allMessages.sort((a, b) => {
            // 客服消息始终在最前面
            if (a.id === 'customer_service') return -1;
            if (b.id === 'customer_service') return 1;

            const timeA = new Date(a.time.replace(/(\d+)分钟前/, (match, minutes) => {
                const now = new Date();
                now.setMinutes(now.getMinutes() - parseInt(minutes));
                return now.toISOString();
            }));
            const timeB = new Date(b.time.replace(/(\d+)分钟前/, (match, minutes) => {
                const now = new Date();
                now.setMinutes(now.getMinutes() - parseInt(minutes));
                return now.toISOString();
            }));
            return timeB - timeA;
        });

        // 计算统计数据
        const unreadCount = allMessages.filter(msg => !msg.isRead).length;
        const todayCount = allMessages.filter(msg =>
            msg.time.includes('刚刚') ||
            msg.time.includes('分钟前') ||
            msg.time.includes('小时前') ||
            msg.time.includes('今天')
        ).length;

        this.setData({
            messages: allMessages,
            filteredMessages: allMessages,
            unreadCount,
            todayCount
        });},

    // 格式化时间
    formatTime(timeStr) {
        if (!timeStr) return '刚刚';

        const now = new Date();
        const time = new Date(timeStr);
        const diff = now - time;
        const minutes = Math.floor(diff / (1000 * 60));
        const hours = Math.floor(diff / (1000 * 60 * 60));
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));

        if (minutes < 1) return '刚刚';
        if (minutes < 60) return `${minutes}分钟前`;
        if (hours < 24) return `${hours}小时前`;
        if (days < 7) return `${days}天前`;

        return time.toLocaleDateString();
    },

    // 获取订单统计数据
    fetchOrderStats() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        if (!token || !riderId) {return;
        }// 获取新订单数量（待接单）
        wx.request({
            url: `${ip}/api/orders/listNoOrdersReceived`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {if (res.data.code === 200) {
                    const allOrders = res.data.data || [];
                    const newOrders = allOrders.filter(item =>
                        item.orderStatusName === '待接单' || item.orderStatus === 1
                    ).length;this.setData({
                        'orderStats.newOrders': newOrders
                    });
                } else {}
            },
            fail: (err) => {}
        });

        // 获取待处理订单数量（配送中）
        wx.request({
            url: `${ip}/api/orders/rider/list?riderId=${riderId}&orderStatus=3`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {if (res.data.code === 200) {
                    const pendingOrders = (res.data.data || []).length;this.setData({
                        'orderStats.pendingOrders': pendingOrders
                    });
                } else {}
            },
            fail: (err) => {}
        });

        // 获取当月收入
        this.fetchMonthlyIncome();
    },

    // 获取客服未读消息数量 - 优化版本
    fetchCustomerServiceUnreadCount() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        if (!token || !riderId) {return;
        }// 使用专门的未读消息数量API
        wx.request({
            url: `${ip}/api/customer-service/message/unread-count`,
            method: 'GET',
            data: {
                userType: 3, // 3-骑手
                userId: riderId
            },
            header: {
                'Authorization': 'Bearer ' + token,
                'content-type': 'application/json'
            },
            success: (res) => {if (res.data.code === 200) {
                    const unreadCount = res.data.data || 0;this.setData({
                        customerServiceUnreadCount: unreadCount
                    });

                    // 重新加载消息数据，客服消息会自动整合进去
                    this.loadMessages();
                } else {this.setData({
                        customerServiceUnreadCount: 0
                    });
                }
            },
            fail: (err) => {this.setData({
                    customerServiceUnreadCount: 0
                });
            }
        });
    },

    // 更新未读数量统计
    updateUnreadCount() {
        const filteredMessages = this.data.filteredMessages || [];
        const unreadCount = filteredMessages.filter(msg => !msg.isRead).length;

        this.setData({
            unreadCount: unreadCount
        });},

    // 获取当月收入 - 使用与profile页面相同的逻辑
    fetchMonthlyIncome() {
        const ip = app.globalData.userIPInfo;
        const token = app.globalData.ridertoken;
        const riderId = app.globalData.riderId;

        if (!token || !riderId) {
            return;
        }// 使用当前月份字符串格式：xxxx-xx月（与profile页面保持一致）
        const now = new Date();
        const currentMonth = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}月`;wx.request({
            url: `${ip}/api/platform/settlement/calculateRiderBonusByMonth?riderId=${riderId}&month=${currentMonth}`,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token
            },
            success: (res) => {
                if (res.data.code === 200) {
                    const monthlyIncome = parseFloat(res.data.data) || 0;

                    this.setData({
                        'orderStats.monthlyIncome': monthlyIncome.toFixed(2)
                    });
                } else {
                    this.setData({
                        'orderStats.monthlyIncome': '0.00'
                    });
                }
            },
            fail: (err) => {
                this.setData({
                    'orderStats.monthlyIncome': '0.00'
                });
            }
        });
    },

    // 初始化数据（保留作为备用方法）
    initData() {
        const {messages} = this.data;
        const unreadCount = messages.filter(msg => !msg.isRead).length;
        const todayCount = messages.filter(msg =>
            msg.time.includes('刚刚') ||
            msg.time.includes('分钟前') ||
            msg.time.includes('小时前') ||
            msg.time.includes('今天')
        ).length;

        this.setData({
            filteredMessages: messages,
            unreadCount,
            todayCount
        });
    },

    // 切换筛选条件
    switchFilter(e) {
        const filter = e.currentTarget.dataset.filter;
        const {messages} = this.data;

        let filteredMessages = [];

        switch (filter) {
            case 'all':
                filteredMessages = [...messages];
                break;
            case 'unread':
                filteredMessages = messages.filter(msg => !msg.isRead);
                break;
            case 'system':
                filteredMessages = messages.filter(msg => msg.type === 'system');
                break;
        }

        this.setData({
            currentFilter: filter,
            filteredMessages
        });

    },

    // 处理消息点击 - 设置订单数据并跳转到配送页面
    handleMessageTap(e) {
        const {id, type} = e.currentTarget.dataset;const message = this.data.messages.find(msg => {
            // 支持字符串和数字ID的比较
            return msg.id === id || msg.id === parseInt(id) || msg.id.toString() === id.toString();
        });if (!message) {wx.showToast({
                title: '消息不存在',
                icon: 'none'
            });
            return;
        }

        // 如果是客服消息，直接跳转到客服页面
        if (message.type === 'customer_service' || message.id === 'customer_service') {// 添加错误处理
            wx.navigateTo({
                url: '/pages/customer-service/index',
                success: () => {},
                fail: (err) => {wx.showToast({
                        title: '页面跳转失败',
                        icon: 'none'
                    });
                }
            });
            return;
        }

        // 标记为已读
        if (!message.isRead) {
            this.markAsRead(id);
        }

        // 根据消息类型确定正确的订单状态
        let orderStatus = '待接单'; // 默认状态

        if (message.title === '配送提醒') {
            orderStatus = '待送达'; // 配送中的订单应该是待送达状态
        } else if (message.title === '送达提醒') {
            orderStatus = '待收货'; // 待收货状态
        } else if (message.title === '新订单通知') {
            orderStatus = '待接单'; // 新订单是待接单状态
        } else if (message.title === '取餐通知') {
            orderStatus = '待取货'; // 待取货状态
        } else if (message.content && message.content.includes('已完成')) {
            orderStatus = '已送达'; // 已完成的订单
        }// 设置订单数据到本地存储
        this.setOrderDataAndNavigate(message, orderStatus);
    },

    // 处理操作按钮 - 设置订单数据并跳转到配送页面
    handleAction(e) {
        const {action, messageId, orderId} = e.currentTarget.dataset;// 找到对应的消息
        const message = this.data.messages.find(msg =>
            msg.id === messageId || msg.id === parseInt(messageId) || msg.id.toString() === messageId.toString()
        );

        switch (action) {
            case 'acceptOrder':
            case 'accept':
                // 立即接单 - 设置订单数据并跳转到配送页面
                wx.showToast({
                    title: '接单成功，进入配送',
                    icon: 'success',
                    duration: 1000
                });
                setTimeout(() => {
                    this.setOrderDataAndNavigate(message, '待取货');
                }, 1000);
                break;
            case 'contactMerchant':
                this.contactMerchant(orderId);
                break;
            case 'contactCustomer':
                this.contactCustomer(orderId);
                break;
            case 'viewOrder':
                this.viewOrder(orderId);
                break;
            case 'viewCustomerService':
                // 跳转到客服页面
                wx.navigateTo({
                    url: '/pages/customer-service/index',
                    success: () => {},
                    fail: (err) => {
                        wx.showToast({
                            title: '页面跳转失败',
                            icon: 'none'
                        });
                    }
                });
                return; // 直接返回，不执行后续的订单处理逻辑
            case 'contact':
                wx.makePhoneCall({
                    phoneNumber: '400-123-4567'
                });
                break;
            default:
                // 其他按钮也设置订单数据并跳转到配送页面
                wx.showToast({
                    title: '正在进入配送',
                    icon: 'loading',
                    duration: 1000
                });
                setTimeout(() => {
                    this.setOrderDataAndNavigate(message);
                }, 1000);
        }
    },

    // 提取订单号并调用接单API，然后跳转到配送页面
    setOrderDataAndNavigate(message, orderStatus = '待接单') {
        if (!message) {
            wx.showToast({
                title: '消息数据错误',
                icon: 'none'
            });
            return;
        }

        // 从消息内容中提取真实订单号
        let orderSn = null;
        const content = message.content || '';

        // 匹配 ORDER 开头的订单号
        const orderMatch = content.match(/ORDER[0-9]+/);
        if (orderMatch) {
            orderSn = orderMatch[0];
        } else {
            wx.showToast({
                title: '订单号提取失败',
                icon: 'none'
            });
            return;
        }

        // 根据订单状态决定处理方式
        if (orderStatus === '待接单') {
            // 新订单需要先接单，然后跳转到待取货状态
            this.callAcceptOrderAPI(orderSn, message);
        } else {
            // 其他状态直接获取订单详情并跳转
            this.fetchOrderDetailAndJump(orderSn, orderStatus);
        }
    },

    // 调用接单API
    callAcceptOrderAPI(orderSn, message) {
        const token = app.globalData.ridertoken;
        const ip = app.globalData.userIPInfo;
        const riderId = app.globalData.riderId;

        if (!token || !riderId) {
            wx.showToast({
                title: '请先登录',
                icon: 'none'
            });
            return;
        }

        wx.request({
            url: `${ip}/api/orders/detail?orderSn=` + orderSn,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token,
            },
            success: (res) => {
                if (res.statusCode === 200 && res.data && res.data.code === 200) {
                    const orderData = res.data.data;

                    // 先调用接单API，然后使用真实订单数据跳转
                    this.assignRiderAndJump(orderSn, orderData);
                } else {
                    wx.showToast({
                        title: res.data?.msg || res.data?.message || '获取订单详情失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    },

    // 调用接单API并跳转
    assignRiderAndJump(orderSn, orderData) {
        const token = app.globalData.ridertoken;
        const ip = app.globalData.userIPInfo;
        const riderId = app.globalData.riderId;

        wx.request({
            url: `${ip}/api/orders/assign-rider`,
            method: 'POST',
            header: {
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: {
                orderSn: orderSn,
                riderId: riderId
            },
            success: (res) => {if (res.data.code === 200) {
                    wx.showToast({
                        title: '接单成功',
                        icon: 'success',
                        duration: 1500
                    });

                    // 接单成功后使用真实订单数据跳转
                    setTimeout(() => {
                        this.setRealOrderDataAndJump(orderData, '待取货');
                    }, 1500);
                } else {
                    wx.showToast({
                        title: res.data.msg || res.data.message || '接单失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    },

    // 获取订单详情并直接跳转（不接单）
    fetchOrderDetailAndJump(orderSn, orderStatus) {
        const token = app.globalData.ridertoken;
        const ip = app.globalData.userIPInfo;wx.request({
            url: `${ip}/api/orders/detail?orderSn=` + orderSn,
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + token,
            },
            success: (res) => {if (res.statusCode === 200 && res.data && res.data.code === 200) {
                    const orderData = res.data.data;// 直接使用真实订单数据跳转
                    this.setRealOrderDataAndJump(orderData, orderStatus);
                } else {wx.showToast({
                        title: res.data?.msg || res.data?.message || '获取订单详情失败',
                        icon: 'none'
                    });

                    // 如果获取详情失败，使用模拟数据this.setOrderDataAndJump(orderSn, orderStatus, null);
                }
            },
            fail: (err) => {wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });

                // 如果请求失败，使用模拟数据this.setOrderDataAndJump(orderSn, orderStatus, null);
            }
        });
    },

    // 使用真实订单数据设置并跳转 - 按照首页格式处理
    setRealOrderDataAndJump(orderData, orderStatus) {
        try {// 按照首页格式处理数据 - 完全一致的结构
            // 处理商家经纬度 - 从 merchantlatAndLng 字段拆分
            const [pickupLat = 0, pickupLng = 0] = (orderData.merchantlatAndLng || '').split(',').map(Number);

            // 处理用户经纬度 - 从 userlatAndLng 字段拆分
            const [deliveryLat = 0, deliveryLng = 0] = (orderData.userlatAndLng || '').split(',').map(Number);

            // 构造与首页完全一致的 order 对象
            const order = {
                id: orderData.id?.toString() || '',
                title: orderData.merchantName || '未知商家',
                userId: orderData.userId,
                pickup: {
                    latitude: pickupLat,
                    longitude: pickupLng,
                    address: orderData.merchantTotalAddress || orderData.addressDetail || `${orderData.province || ''} ${orderData.city || ''} ${orderData.district || ''}`.trim()
                },
                delivery: {
                    latitude: deliveryLat,
                    longitude: deliveryLng,
                    address: orderData.addressDetail || `${orderData.province || ''} ${orderData.city || ''} ${orderData.district || ''}`.trim()
                },
                distance: '计算中...',
                eta: '计算中...',
                income: orderData.paidAmount || 0,
                statusText: orderData.orderStatusName || orderStatus,
                orderSn: orderData.orderSn || '',
                goodsInfoList: Array.isArray(orderData.goodsInfoList) ? orderData.goodsInfoList.map(goods => ({
                    name: goods.name || '',
                    count: goods.count || 0,
                    skuName: goods.sku?.name || '',
                    relatedOrders: goods.relatedOrders || []
                })) : []
            };// 按照首页 goToMap 函数的完全相同逻辑存储数据
            const pickup = encodeURIComponent(JSON.stringify(order.pickup));
            const delivery = encodeURIComponent(JSON.stringify(order.delivery));
            const statusText = order.statusText;
            const goods = encodeURIComponent(JSON.stringify(order.goodsInfoList || []));
            const orderSn = order.orderSn;
            const userId = order.userId;

            wx.setStorageSync('pickup', pickup);
            wx.setStorageSync('delivery', delivery);
            wx.setStorageSync('orderStatus', statusText);
            wx.setStorageSync('orderSn', orderSn);
            wx.setStorageSync('userId', userId);
            wx.setStorageSync('goods', goods);// 计算距离和时间，然后跳转
            this.calculateDistanceAndTime(order, () => {
                // 重新存储更新后的数据
                const updatedPickup = encodeURIComponent(JSON.stringify(order.pickup));
                const updatedDelivery = encodeURIComponent(JSON.stringify(order.delivery));

                wx.setStorageSync('pickup', updatedPickup);
                wx.setStorageSync('delivery', updatedDelivery);
                wx.setStorageSync('orderDistance', order.distance);
                wx.setStorageSync('orderEta', order.eta);// 跳转到配送页面
                wx.switchTab({
                    url: '/pages/order/index'
                });
            });

        } catch (error) {wx.showToast({
                title: '数据处理失败',
                icon: 'none'
            });
        }
    },

    // 获取并存储当前位置
    getCurrentLocation(callback) {
        // 先检查本地存储是否有位置信息（1小时内有效）
        const storedLocation = wx.getStorageSync('riderLocation');
        if (storedLocation && storedLocation.timestamp) {
            const now = Date.now();
            const oneHour = 60 * 60 * 1000; // 1小时
            if (now - storedLocation.timestamp < oneHour) {if (callback) callback(storedLocation);
                return;
            }
        }// 先检查授权状态
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userLocation']) {
                    // 已授权，直接获取位置
                    this.getLocationDirect(callback);
                } else {
                    // 未授权，请求授权
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success: () => {this.getLocationDirect(callback);
                        },
                        fail: () => {wx.showModal({
                                title: '位置权限',
                                content: '需要获取您的位置信息来计算配送距离，请在设置中开启位置权限',
                                showCancel: false,
                                confirmText: '知道了'
                            });
                            if (callback) callback(null);
                        }
                    });
                }
            },
            fail: () => {if (callback) callback(null);
            }
        });
    },

    // 直接获取位置
    getLocationDirect(callback) {
        wx.getLocation({
            type: 'gcj02',
            isHighAccuracy: true,
            success: (res) => {
                const location = {
                    latitude: res.latitude,
                    longitude: res.longitude,
                    timestamp: Date.now()
                };

                // 存储到本地
                wx.setStorageSync('riderLocation', location);

                if (callback) callback(location);
            },
            fail: (error) => {

                // 根据错误类型给出不同提示
                let errorMsg = '获取位置失败';
                if (error.errMsg.includes('auth deny')) {
                    errorMsg = '位置权限被拒绝';
                } else if (error.errMsg.includes('timeout')) {
                    errorMsg = '获取位置超时';
                } else if (error.errMsg.includes('system deny')) {
                    errorMsg = '系统拒绝位置访问';
                }

                wx.showToast({
                    title: errorMsg,
                    icon: 'none',
                    duration: 2000
                });

                if (callback) callback(null);
            }
        });
    },

    // 计算距离和时间
    calculateDistanceAndTime(order, callback) {
        const app = getApp();
        const key = app.globalData.locationKey;

        if (!key) {if (callback) callback();
            return;
        }

        // 根据订单状态决定计算方式
        const orderStatus = order.statusText;if (orderStatus === '待拿货' || orderStatus === '待取货') {
            // 待拿货：计算从当前位置到商家的距离
            this.calculateRiderToMerchant(order, callback);
        } else if (orderStatus === '待收货' || orderStatus === '配送中') {
            // 待收货：计算从当前位置到用户的距离
            this.calculateRiderToUser(order, callback);
        } else {
            // 其他状态：计算商家到用户的距离（原逻辑）
            this.calculateMerchantToUser(order, callback);
        }
    },

    // 计算骑手到商家的距离（待拿货状态）
    calculateRiderToMerchant(order, callback) {
        this.getCurrentLocation((riderLocation) => {
            if (!riderLocation) {
                order.distance = '位置获取失败';
                order.eta = '位置获取失败';
                if (callback) callback();
                return;
            }

            if (!order.pickup.latitude || !order.pickup.longitude) {order.distance = '数据无效';
                order.eta = '数据无效';
                if (callback) callback();
                return;
            }

            const from = `${riderLocation.latitude},${riderLocation.longitude}`;
            const to = `${order.pickup.latitude},${order.pickup.longitude}`;this.callMapAPI(from, to, order, callback, '骑手→商家');
        });
    },

    // 计算骑手到用户的距离（待收货状态）
    calculateRiderToUser(order, callback) {
        this.getCurrentLocation((riderLocation) => {
            if (!riderLocation) {
                order.distance = '位置获取失败';
                order.eta = '位置获取失败';
                if (callback) callback();
                return;
            }

            if (!order.delivery.latitude || !order.delivery.longitude) {order.distance = '数据无效';
                order.eta = '数据无效';
                if (callback) callback();
                return;
            }

            const from = `${riderLocation.latitude},${riderLocation.longitude}`;
            const to = `${order.delivery.latitude},${order.delivery.longitude}`;this.callMapAPI(from, to, order, callback, '骑手→用户');
        });
    },

    // 计算商家到用户的距离（默认状态）
    calculateMerchantToUser(order, callback) {
        // 检查经纬度是否有效
        if (!order.pickup.latitude || !order.pickup.longitude ||
            !order.delivery.latitude || !order.delivery.longitude) {order.distance = '数据无效';
            order.eta = '数据无效';
            if (callback) callback();
            return;
        }

        const from = `${order.pickup.latitude},${order.pickup.longitude}`;
        const to = `${order.delivery.latitude},${order.delivery.longitude}`;this.callMapAPI(from, to, order, callback, '商家→用户');
    },

    // 调用地图API的通用方法
    callMapAPI(from, to, order, callback, description) {
        const app = getApp();
        const key = app.globalData.locationKey;wx.request({
            url: `https://apis.map.qq.com/ws/direction/v1/driving/?from=${from}&to=${to}&key=${key}`,
            success: (res) => {if (res.data.status === 0 && res.data.result.routes.length > 0) {
                    const route = res.data.result.routes[0];
                    const distance = (route.distance / 1000).toFixed(1); // 转换为公里
                    const durationSeconds = route.duration; // API返回的是秒// 根据距离合理估算时间
                    let estimatedTime;
                    const distanceKm = parseFloat(distance);

                    if (distanceKm < 5) {
                        // 5公里以内，按30km/h计算（城市道路）
                        estimatedTime = Math.ceil((distanceKm / 30) * 60); // 分钟
                    } else if (distanceKm < 50) {
                        // 50公里以内，按50km/h计算（城市+郊区）
                        estimatedTime = Math.ceil((distanceKm / 50) * 60); // 分钟
                    } else if (distanceKm < 200) {
                        // 200公里以内，按80km/h计算（高速）
                        estimatedTime = Math.ceil((distanceKm / 80) * 60); // 分钟
                    } else {
                        // 超过200公里，按100km/h计算，但转换为小时显示
                        const hours = (distanceKm / 100).toFixed(1);
                        estimatedTime = `${hours}小时`;
                    }

                    order.distance = `${distance}km`;
                    order.eta = typeof estimatedTime === 'number' ? `${estimatedTime}分钟` : estimatedTime;} else {order.distance = '计算失败';
                    order.eta = '计算失败';
                }

                if (callback) callback();
            },
            fail: (error) => {order.distance = '网络错误';
                order.eta = '网络错误';
                if (callback) callback();
            }
        });
    },

    // 设置订单数据并跳转 - 使用模拟数据作为备用方案
    setOrderDataAndJump(orderSn, orderStatus, message) {// 创建模拟的订单数据，按照首页格式
        const mockOrderData = {
            id: 999,
            merchantName: '麦当劳(科技园店)',
            userId: app.globalData.riderId || '1',
            merchantlatAndLng: '22.5431,114.0579',
            userlatAndLng: '22.5331,114.0679',
            addressDetail: '深圳市南山区科技园南区',
            province: '广东省',
            city: '深圳市',
            district: '南山区',
            paidAmount: 47.0,
            orderStatusName: orderStatus,
            orderSn: orderSn,
            goodsInfoList: [
                {
                    name: '巨无霸套餐',
                    count: 1,
                    sku: { name: '去冰，少糖' },
                    relatedOrders: []
                },
                {
                    name: '薯条(大)',
                    count: 1,
                    sku: { name: '加盐' },
                    relatedOrders: []
                }
            ]
        };

        // 使用相同的处理逻辑
        this.setRealOrderDataAndJump(mockOrderData, orderStatus);
    },

    // 接单操作 - 设置订单数据并跳转到配送页面
    acceptOrder(orderId) {// 创建一个模拟消息对象
        const mockMessage = {
            id: orderId || 'mock_order',
            content: `您有一单新的外卖订单，订单号：${orderId || 'LX202506190001'}，配送费：¥8.5`
        };

        wx.showToast({
            title: '接单成功，进入配送',
            icon: 'success',
            duration: 1000
        });

        setTimeout(() => {
            this.setOrderDataAndNavigate(mockMessage, '待取货');
        }, 1000);
    },

    // 联系商家
    contactMerchant(orderId) {
        wx.showActionSheet({
            itemList: ['拨打电话', '发送消息'],
            success: (res) => {
                if (res.tapIndex === 0) {
                    wx.makePhoneCall({
                        phoneNumber: '400-123-4567'
                    });
                } else {
                    wx.showToast({
                        title: '消息功能开发中',
                        icon: 'none'
                    });
                }
            }
        });
    },

    // 联系客户
    contactCustomer(orderId) {
        wx.showActionSheet({
            itemList: ['拨打电话', '发送消息'],
            success: (res) => {
                if (res.tapIndex === 0) {
                    wx.makePhoneCall({
                        phoneNumber: '138-0000-0000'
                    });
                } else {
                    wx.showToast({
                        title: '消息功能开发中',
                        icon: 'none'
                    });
                }
            }
        });
    },

    // 查看订单详情
    viewOrder(orderId) {
        wx.navigateTo({
            url: `/pages/order-detail/index?orderId=${orderId}`
        });
    },

    // 标记单条消息为已读
    markAsRead(messageId) {
        const {messages} = this.data;
        const updatedMessages = messages.map(msg => {
            // 支持字符串和数字ID的比较
            if (msg.id === messageId || msg.id === parseInt(messageId) || msg.id.toString() === messageId.toString()) {
                return {...msg, isRead: true};
            }
            return msg;
        });

        this.setData({
            messages: updatedMessages
        });

        this.initData();
    },

    // 全部标记为已读
    markAllRead() {
        wx.showModal({
            title: '确认操作',
            content: '确定要将所有消息标记为已读吗？',
            success: (res) => {
                if (res.confirm) {
                    const {messages} = this.data;
                    const updatedMessages = messages.map(msg => ({...msg, isRead: true}));

                    this.setData({
                        messages: updatedMessages
                    });

                    this.initData();

                    wx.showToast({
                        title: '已全部标记为已读',
                        icon: 'success'
                    });
                }
            }
        });
    },

    // 清空消息
    clearMessages() {
        wx.showModal({
            title: '确认清空',
            content: '确定要清空所有消息吗？此操作不可恢复。',
            confirmColor: '#ff4d4f',
            success: (res) => {
                if (res.confirm) {
                    this.setData({
                        messages: [],
                        filteredMessages: [],
                        unreadCount: 0,
                        todayCount: 0
                    });

                    wx.showToast({
                        title: '消息已清空',
                        icon: 'success'
                    });
                }
            }
        });
    },

    // 跳转到客服页面
    goToCustomerService() {
        wx.navigateTo({
            url: '/pages/customer-service/index'
        });
    }
});
